#!/usr/bin/env python3
import argparse
import json
import sys
import os
import requests

USAGE = """
        {} --help
        {} --server SERVER --version_control {{github|gitlab|svn}} --repo REPO --branch BRANCH \\
                              --scm_repo SCM_REPO --scm_branch SCM_BRANCH --enabled ENABLED
        {} --server SERVER --file FILE
        {} --server SERVER --dir DIR
""".format(*([os.path.basename(__file__)] * 4))

parser = argparse.ArgumentParser(usage=USAGE, description="command line to create/update patch tracking item")

parser.add_argument("--server", default="127.0.0.1:5001", help="patch tracking daemon server, default: 127.0.0.1:5001")

parser.add_argument("--version_control", default='github', choices=['github', 'gitlab', 'svn'])
parser.add_argument("--repo")
parser.add_argument("--branch")
parser.add_argument("--scm_repo")
parser.add_argument("--scm_branch")
parser.add_argument("--enabled")

parser.add_argument('--file', help='import patch tracking from file')

parser.add_argument('--dir', help='import patch tracking from files in directory')

args = parser.parse_args()

style1 = args.version_control or args.repo or args.branch or args.scm_repo or args.scm_branch or args.enabled
style2 = bool(args.file)
style3 = bool(args.dir)

if str([style1, style2, style3]).count('True') >= 2:
    print("mix different usage style")
    parser.print_usage()
    sys.exit(-1)


def single_input_track(params, file_path=None):
    if param_check(params, file_path) == 'error':
        return 'error', 'params error'

    repo = params['repo']
    branch = params['branch']
    scm_repo = params['scm_repo']
    scm_branch = params['scm_branch']
    version_control = params['version_control']
    enabled = params['enabled'].lower()
    server = params['server']

    enabled = bool(enabled)
    url = '/'.join(['http:/', server, 'tracking'])
    data = {
        'version_control': version_control,
        'scm_repo': scm_repo,
        'scm_branch': scm_branch,
        'repo': repo,
        'branch': branch,
        'enabled': enabled
    }
    ret = requests.post(url, json=data)
    if ret.status_code == 201:
        return 'success', 'created'

    if ret.status_code == 204:
        return 'success', 'updated'

    msg = 'Tracking failed. \nReturn code: {} \nMessage: {}'.format(ret.status_code, json.loads(ret.text)['message'])
    return 'error', msg


def file_input_track(file_path):
    if os.path.exists(file_path) and os.path.isfile(file_path):
        with open(file_path) as file:
            content = file.readlines()
            params = dict()
            for item in content:
                k = item.split(':')[0]
                value = item.split(':')[1].strip(' ').strip('\n')
                if k == 'src_repo':
                    k = 'scm_repo'
                if k == 'src_branch':
                    k = 'scm_branch'
                if k == 'patch_tracking_enabled':
                    k = 'enabled'
                params.update({k: value})
            params.update({'server': args.server})
            return single_input_track(params, file_path), file_path
    else:
        return (('error', 'yaml path error'), file_path)


def dir_input_track(dir_path):
    if os.path.exists(dir_path) and os.path.isdir(dir_path):
        for root, _, files in os.walk(dir_path):
            ret_lst = list()
            for file in files:
                if os.path.splitext(file)[-1] == ".yaml":
                    file_path = os.path.join(root, file)
                    ret_lst.append(file_input_track(file_path))
            return ret_lst
    else:
        return [(('error', 'dir path error'), dir_path)]


def param_check(params, file_path=None):
    flag = 0
    required_param = ['version_control', 'scm_repo', 'scm_branch', 'repo', 'branch', 'enabled']
    for req in required_param:
        if req not in params:
            if file_path:
                print(f'param: --{req} must be configured. Error in {file_path}')
            else:
                print(f'param: --{req} must be configured.')
            flag = 1
    for k, value in params.items():
        if not value:
            if file_path:
                print(f'param: --{k} must be configured. Error in {file_path}')
            else:
                print(f'param: --{k} cannot be empty.')
            flag = 1
    if flag:
        return 'error'
    return None


def main():
    if style2:
        ret = file_input_track(args.file)
        if ret[0][0] == 'success':
            print('Tracking successfully {}.'.format(ret[0][1]))
        else:
            print(ret[0][1])
    elif style3:
        ret = dir_input_track(args.dir)
        for item in ret:
            if item[0][0] == 'success':
                print(f'Tracking successfully {item[0][1]} for {item[1]}.')
            else:
                print(f'Tracking failed. Params error in file {item[1]}')
    else:
        params = {
            'repo': args.repo,
            'branch': args.branch,
            'scm_repo': args.scm_repo,
            'scm_branch': args.scm_branch,
            'version_control': args.version_control,
            'enabled': args.enabled,
            'server': args.server
        }
        ret = single_input_track(params)
        if ret[0] == 'success':
            print('Tracking successfully {}.'.format(ret[1]))
        else:
            print(ret[1])


if __name__ == '__main__':
    main()
